<template>
  <div>
    <el-tabs type="border-card" v-model="activname" @tab-click="switchTab">
      <el-tab-pane
        v-for="item in TAB_LISTS"
        :key="item.name"
        :disabled="tableInfo.loading"
        :label="item.title"
        :name="item.name"
      />
      <BasicForm
        ref="formData"
        :menuId="menuId"
        needSetSearchFields
        formItemWidth="100px"
        :formColumns="formItems"
        :dataSource="formData"
        :handleSearchForm="handleQueryForm"
        @getFormData="getFormData"
        @getSearchFormFields="getSearchFormFields"
      />
      <el-card class="sourcing-table-card" shadow="never">
        <el-row slot="header" type="flex" justify="space-between" align="middle">
          <span>数据列表</span>
          <el-button
            size="mini"
            :loading="exportLoading"
            @click="exportTableData"
          >导出</el-button>
        </el-row>
        <BasicList
          showActionCol
          :loading="tableInfo.loading"
          :show-select-col="false"
          :data-source="tableInfo.list"
          :columns="columns"
          :actionColWidth="actionColWidth"
          :tableHeight="493"
          :actionRender="renderTableBtnAction"
          :pagination="pagination"
          :total="total"
          @pageChange="handlePageChange"
          @pageSizeSelect="handlePageSizeChange"
        />
      </el-card>
    </el-tabs>
    <!-- 询价取消 -->
    <InquiryDialog
      :visible.sync="inqueryFlag"
      :setdiolagdata="setdiolagdata"
    />
    <!-- 合同查看 -->
    <ContractDialog
      :visible.sync="contractVisible"
      :sourcingBillId="sourcingBillId"
    />
    <!-- 附件查看 -->
    <AttachmentDialog
      :visible.sync="attachDialogVisible"
      :fileGroupId="fileGroupId"
    />
    <!-- 合同签订 -->
    <SignContractInfo
      :visible.sync="signContractInfo.visible"
      :supplierInfo="signContractInfo.supplierInfo"
      @signContractCallback="signContractCallback"
    />
  </div>
</template>

<script>
import InquiryDialog from '@sourcing/demand-manage/elDialog/InquiryDialog';
import ContractDialog from '../components/ContractDialog';
import SignContractInfo from './components/SignContractInfo';
import BasicList from '@sourcing/components/BasicList';
import BasicForm from '@sourcing/components/BasicForm';
import BasicPage from '@/mixins/sourcing/basicPage';
import SearchFields from '@/mixins/sourcing/searchFields';
import AttachmentDialog from '@sourcing/components/AttachmentDialog';
import { handleOpenNewPageByName } from '../../utils'
import { createExcelByExport } from '@/utils/bizUtils';
import { getTableAction } from '@/utils/getBtnsRender';
import {
  getTableColumns,
  getTableColumnsForGenerate,
  TAB_LISTS, FORM_ITEMS,
  ACTION_WIDTH_OBJ
} from './constants';
import {
  getOrderInquiryListService,
  exportOrderInquiryListService,
  reinquiryForGenerateOrderService,
  getOAUrlService,
  exportOrderContractService,
  checkSupplierContractService,
  getOrderListForGeneratedService,
  exportOrderListForGeneratedService,
} from '@/api/sourcing/purchaseInquiry'

export default {
  mixins: [BasicPage, SearchFields],
  components: {
    BasicList,
    BasicForm,
    InquiryDialog,
    ContractDialog,
    AttachmentDialog,
    SignContractInfo
  },
  data () {
    return {
      menuId: 202,
      formItems: FORM_ITEMS,
      TAB_LISTS,
      fileGroupId: null,
      attachDialogVisible: false,
      contractVisible: false, // 查看合同弹框
      activname: '', // 当前选中的
      inqueryFlag: false,
      setdiolagdata: { tabtype: 3 },
      columns: [],
      sourcingBillId: null,
      signContractInfo: {
        visible: false,
        supplierInfo: {}, // 需要签订合同的供应商信息
      }
    };
  },
  computed: {
    actionColWidth () {
      return ACTION_WIDTH_OBJ[this.activname] || 120
    },
  },
  methods: {
    init () {
      const { sts } = this.$route.query;
      if (sts) {
        this.activname = sts
        this.formData.billStatus = sts
        this.getTableData();
      }
      this.initTabelColumns(sts)
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const actionList = [
        { label: '查看', method: this.handleView },
      ]
      // 询价中
      if (row.billStatus == 100) {
        actionList.push({ label: '询价取消', method: this.handleCancelInquery })
      }
      // 待订货审批
      if (row.billStatus == 200) {
        actionList.push({ label: '审批流', method: this.handleAudit })
      }
      // 待生成订单
      if (this.formData.billStatus == '300' && row.billStatus == 300) {
        // 待确认货物处理方式状态 1-无需确认，2待确认，3-同意，4-不同意
        // 二次定价状态 1-无需二次定价 2 待二次定价 3-已二次定价
        /* if ((row.goodsHandleModeStatus == 1 || row.goodsHandleModeStatus == 3) && row.secondPriceStatus !== 2) {
          actionList.push(
            { label: '生成订单', method: this.handleGenerateOrder },
          )
        } */
        actionList.push(
          { label: '生成订单', method: this.handleGenerateOrder },
          { label: '重新询价', method: this.handleReinquiry },
          { label: '导出合同', method: this.exportContractfn }
        )
      }
      return getTableAction({ h, row, actionList })
    },
    // 获取订货列表
    async getTableData (pageNum) {
      if (pageNum) {
        this.pagination.pageNum = pageNum;
      }
      const data = {
        condition: this.formData,
        ...this.pagination
      };
      let res = null;
      if (this.formData.billStatus == 300) {
        // 待生成订单列表信息
        res = await getOrderListForGeneratedService(
          data,
          state => { this.tableInfo.loading = state }
        )
      } else {
        res = await getOrderInquiryListService(
          data,
          state => { this.tableInfo.loading = state }
        )
      }
      if (res) {
        const { data, rowCount } = res.data;
        this.tableInfo.list = data || [];
        this.total = rowCount || 0;
      } else {
        this.tableInfo.list = [];
        this.total = 0;
      }
    },
    exportTableData () {
      if (this.formData.billStatus == 300) {
        this.exportOrderList();
      } else {
        this.exportData();
      }
    },
    // 数据导出
    async exportData () {
      const res = await exportOrderInquiryListService(
        this.formData,
        state => { this.exportLoading = state }
      )
      if (res) {
        createExcelByExport({ res, excelTitle: '订货询价列表' });
      }
    },
    // 导出待生成订单列表
    async exportOrderList () {
      const res = await exportOrderListForGeneratedService(
        this.formData,
        state => { this.exportLoading = state }
      )
      if (res) {
        createExcelByExport({ res, excelTitle: '待生成订单订货询价列表' });
      }
    },
    // 查看合同信息
    queryContractInfoAction (row) {
      this.contractVisible = true;
      this.sourcingBillId = row.sourcingBillId;
    },
    // 初始化表头
    initTabelColumns (type) {
      if (type == 200) {
        this.columns = _.cloneDeep(getTableColumns(this))
      } else if (type == 300) {
        this.columns = _.cloneDeep(getTableColumnsForGenerate(this))
      } else {
        this.columns = _.cloneDeep(getTableColumns(this)).filter(item => !item.isPending)
      }
    },
    // 切换tab
    switchTab (target) {
      this.$refs['formData'].handleResetForm();
      const type = target.name;
      this.formData.billStatus = type;
      this.initTabelColumns(type)
      this.$nextTick(() => {
        this.handlePageChange(1)
      })
    },
    handleView (row) {
      let nameUrl = '';
      let query = {};
      let detailInfo = {
        pageType: 2,
        sourcingBillId: row.sourcingBillId,
        isEdit: false,
      };
      if (row.billStatus == (400 || 200 || 300)) {
        sessionStorage.setItem('isCompleteWinBill', 1)
        detailInfo.isEdit = false;
        nameUrl = 'orderCalibrationView';
      } else if (row.billStatus == 150) { // 等待商品准入审批
        // 0-无需审批，100-待审批，200-审批驳回，300-审批通过
        if (row.canEdit) {
          sessionStorage.setItem('isCompleteWinBill', 1)
          nameUrl = 'orderCalibration';
          query = { isReject: true };
          detailInfo.isEdit = true;
        } else {
          nameUrl = 'orderCalibrationView';
          detailInfo.isEdit = false;
        }
      } else {
        nameUrl = 'purchaseDetail';
        if (row.billStatus == 100) {
          detailInfo.isEdit = true;
        } else {
          detailInfo.isEdit = false;
        }
      }
      this.setStorgeFn(detailInfo)
      handleOpenNewPageByName(this, nameUrl, query)
    },
    // 询价取消
    handleCancelInquery (row) {
      this.setdiolagdata.selectionChangeval = row.sourcingBillId
      this.inqueryFlag = true;
    },
    // 查看审批流
    async handleAudit (row) {
      const res = await getOAUrlService(
        { flowId: row.flowId },
        state => { this.tableInfo.loading = state }
      )
      if (res) {
        window.open(res.data)
      }
    },
    // 生成订单 判断单据下商品是否为待二次询价，是否是线索供应商
    async handleGenerateOrder (row) {
      // 已上传且签订合同，下推采购订单直接跳转至采购订单页面
      const res = await checkSupplierContractService(
        { sourcingSupplierId: row.sourcingSupplierId },
        state => { this.tableInfo.loading = state }
      )
      if (res) {
        const { data } = res;
        // 是否已上传合同  1是，2否
        if (data == 1) {
          this.signContractCallback(row)
        } else if (data == 2) {
          this.signContractInfo.supplierInfo = {
            sourcingSupplierId: row.sourcingSupplierId,
            supplierName: row.supplierName,
            supplierId: row.supplierId,
          };
          this.signContractInfo.visible = true;
        }
      }
    },
    // 导出合同
    async exportContractfn (row) {
      const res = await exportOrderContractService(
        { sourcingSupplierId: row.sourcingSupplierId },
        state => { this.tableInfo.loading = state }
      )
      if (res) {
        createExcelByExport({ res, excelTitle: '商品订货合同' });
      }
    },
    // 重新询价
    handleReinquiry (row) {
      this.$confirm('您确定要重新询价吗，历史定标结果将会清空', '提示', {
        type: 'warning',
      }).then(() => {
        this.reinquiryAction(row)
      }).catch(() => {});
    },
    // 重新询价接口调用
    async reinquiryAction (row) {
      const res = await reinquiryForGenerateOrderService(
        { sourcingSupplierId: row.sourcingSupplierId },
        state => { this.tableInfo.loading = state }
      )
      if (res?.data) {
        const detailInfo = {
          pageType: 2,
          isEdit: true,
          sourcingBillId: res.data,
        };
        // 跳转至 详情报价页
        this.$router.push({ name: 'purchaseDetail' })
        this.setStorgeFn(detailInfo)
      }
    },
    // 签订合同回调
    signContractCallback (row) {
      const {
        supplierId,
        sourcingSupplierId
      } = row;
      handleOpenNewPageByName(
        this,
        'pushDownPage',
        { supplierId, sourcingSupplierId }
      )
    },
    // 查看附件
    handleViewFileList (row) {
      this.fileGroupId = row.fileGroupId;
      this.attachDialogVisible = true;
    },
    // 获取分类Id
    getCategoryUuid (val) {
      this.formData.categoryCode = val;
    },
    // 查看审核详情
    handleViewAuditDetail (row) {
      // 0-无需审批，100-待审批，200-审批驳回，300-审批通过
      handleOpenNewPageByName(this, 'latentProductRecordList', { orderInquiryNo: row.sourceBillNo })
    },
    setStorgeFn (param) {
      sessionStorage.setItem('detailInfo', JSON.stringify(param));
    },
  },
};
</script>
